/**
 * @file: 
 * @author: Lengxx
 * @date: 2024-06-20
 */
<template>
  <ICheckbox>
    <ICheckboxItem 
    v-for="item in props.items" 
    :key="item.value" 
    @change="onSelect"
    :data="item"
    :checked="getDefaultValue(item.value)" >{{ item.label }}</ICheckboxItem>
  </ICheckbox>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import { cloneDeep } from 'lodash-es'
import ICheckbox from './index.vue'
import ICheckboxItem from './ICheckboxItem.vue'
import { ICheckboxEmits, ICheckboxItemProps } from './types'

const props = defineProps<{
  items: ICheckboxItemProps[],
  defaultValue: string[]
}>()

const emits = defineEmits<{
  (e: 'change', value: string[], node: ICheckboxItemProps[]): void
}>()

const selectList = reactive<string[]>([]);
const nodeList = reactive<ICheckboxItemProps[]>([])

function getDefaultValue(itemValue: string) {
  return props.defaultValue.includes(String(itemValue))
}

function onSelect(data: ICheckboxEmits) {
  if (data.checked) {
    selectList.push(data.value)
    nodeList.push(data);
  } else {
    const index = selectList.findIndex(item => item === data.value)
    selectList.splice(index, 1)
    nodeList.splice(index, 1);
  }

  emits('change', cloneDeep(selectList), cloneDeep(nodeList))
}

</script>

